package com.cosina.game.fly;

import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.microedition.khronos.opengles.GL10;

public class Game {
	List<Block> blocks = new ArrayList<Block>();
	
	private int lastRow = -18;
	public Game(){
		for(int i=-8; i>lastRow;i--){
			gen2New(i);
		}
	}
	
	boolean generation = false;
	private void update() {
		Iterator<Block> blockIter = blocks.iterator();
		while(blockIter.hasNext()){
			Block each = blockIter.next();
			each.moveOut();
			if(each.dead()){
				blockIter.remove();
			}
		}
		generation = !generation;
		if(generation)
			gen2New(lastRow);
	}
	
	private Random random = new Random();
	private void gen2New(int row){
		int xIndex = random.nextInt(16)-8;
		blocks.add(new Block(xIndex, row));
		if(random.nextBoolean() == true){
			int xIndex2 = random.nextInt(16)-8;
			if(xIndex2 != xIndex)
				blocks.add(new Block(xIndex2, row));
		}
	}
	
	private FloatBuffer ground = FloatBuffer.wrap(new float[]{
			-15f,-2f,-20f,
			15f,-2f,-20f,
			-15f,-2f,0f,
			15f,0-2f,0f,
	});
	int movePart = 0;
	public void draw(GL10 gl){
		gl.glTranslatef(0, 0, movePart/5);
		gl.glColor4f(
				Constants.GROUD_COLOR[0], 
				Constants.GROUD_COLOR[1], 
				Constants.GROUD_COLOR[2], 
				Constants.GROUD_COLOR[3]);
		
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, ground);
		gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
		
		for(Block each : blocks){
			gl.glTranslatef(each.x, each.y, each.z);
			gl.glColor4f(each.rgba[0], each.rgba[1], each.rgba[2], each.rgba[3]);
			gl.glVertexPointer(3, GL10.GL_FLOAT, 0, Block.vertextsBuffer);
			
			gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 24);

//			gl.glColor4f(0f, 0f, 0f, each.rgba[3]);
//			gl.glVertexPointer(3, GL10.GL_FLOAT, 0, Block.vertextsBuffer);
//			gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, 24);
			gl.glTranslatef(-each.x, -each.y, -each.z);
		}
		
		movePart ++;
		if(movePart == 5){
			update();
			movePart = 0;
		}
	}

}
